<template>
    <s-card title="配置">
       <s-upload
          @onSuccess="onSucessUpload"
          style="position: relative; display: inline-block"
          :class="[{ m_bottom: state.file }]"
       >
          <s-button style="margin-right:16px">浏览</s-button>
          <span v-if="state.file" class="file_position">
             <s-icon type="icon-file" /> {{ state.file.name }}
          </span>
       </s-upload>
       <s-button type="primary" @click="handleImport">导入配置</s-button>
       <s-button type="primary" @click="handleExport" style="margin-left:16px">导出配置</s-button>
    </s-card>
    <s-modal
      v-model:show="loadShow"
      :title="tip"
      :before-close="closeLoad"
      :show-close="showClose"
   >
      <s-progress :type="progressType"/>
   </s-modal>
 </template>

<script lang="ts" setup>
import { SCard, SUpload, Message, SButton, SIcon, SModal, SProgress } from "@/components"
import { reactive, toRaw } from "vue"
import { useLoad } from "@/hooks"
import { importConfig, exportConfig } from "@/request"
import { download } from "@/utils"
const {
   STATUS,
   tip,
   loadShow,
   closeLoad,
   changeStatus,
   goReboot,
   showClose,
   progressType
} = useLoad()
interface State {
    file: any;
}
const state = reactive<State>({
   file: null
})

// 获取文件
const onSucessUpload = (fileList: FileList) => {
   state.file = fileList[0]
}

// 导入配置
const handleImport = () => {
   if (!state.file) {
      return Message.error("请先点击浏览导入文件")
   }
   const fb = new FormData()
   fb.append(state.file.name, toRaw(state.file))
   changeStatus(STATUS.CONFIG_UPLOADING)
   importConfig(fb).then(res => {
      if (res) {
         Message.success("导入成功")
         changeStatus(STATUS.CONFIG_REBOOTING)
         goReboot()
      } else {
         changeStatus(STATUS.CONFIG_ERROR)
      }
   })
}

// 导出配置
const handleExport = () => {
   exportConfig().then(data => {
      const uri = data.uri as string
      const fileName = uri.slice(uri.lastIndexOf("/") + 1)
      download(uri, fileName)
   })
}

</script>

 <style scoped lang="less">
    .m_bottom {
       margin-bottom: 40px;
    }

    .file_position {
       cursor: default;
       position: absolute;
       width: 620px;
       top: 38px;
       left: 0px;
    }
 </style>
